package com.example.form.controller;

import com.example.form.common.AppResult;
import com.example.form.common.ResultCode;
import com.example.form.config.AppConfig;
import com.example.form.model.Message;
import com.example.form.model.User;
import com.example.form.service.IMessageService;
import com.example.form.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@Api(tags ="站内信接口")
@RestController
@RequestMapping("/message")
public class MessageController {
    @Resource
    private IMessageService messageService;//注入操作站内信表的实现类
    @Resource
    private IUserService userService;//注入操作用户表的实现类

    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam(value = "接收⽤⼾Id") @RequestParam(value = "receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam(value = "站内信内容") @RequestParam(value = "content") @NonNull String content){
        //获取当前登录用户信息
        HttpSession session= request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        //1,验证当前用户登录状态,禁言则不能发
        if(user.getState()==1){
            //返回用户异常
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);//已经被禁言
        }
        //2,不能给自己发送站内信
        if(user.getId()==receiveUserId){//发送者id等于接收者id
            return AppResult.failed("不能给自己发送站内信");
        }
        //3,校验接受者是否存在
        User receiveUser=userService.selectById(receiveUserId);//根据传入的接收者id查询
        if (receiveUser == null || receiveUser.getDeleteState() != 0) {//不存在或者被删除
            // ⽇志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", receiveUserId = " + receiveUserId);
                    // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //4,封装对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        // 调⽤业务层
        messageService.create(message);
        // 返回结果
        return AppResult.success();
    }

    @ApiOperation("获取未读站内信数量")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request){
        //获取登录用户的信息
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        //查询未读信息的数量
        int count= messageService.selectUnreadCount(user.getId());//当前登录用户的id就是接收者id
        //返回查询到的结果
        return AppResult.success(count);
    }

    @ApiOperation("查询用户所有的站内信列表")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request){
        //获取登录用户
        HttpSession session= request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service
        List<Message> messages=messageService.selectByReceiveUserId(user.getId());
        //返回结果
        return AppResult.success(messages);
    }
    @ApiOperation("更新站内信状态")
    @PostMapping("markRead")
    public AppResult markRead(HttpServletRequest request,
                              @ApiParam("站内信id") @RequestParam("id")@NonNull Long id){
        //1,根据id查询站内信
        Message message=messageService.selectById(id);
        //2,检验站内信是否存在
        if (message==null||message.getDeleteState()==1){//不存在或者已删除
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);//资源不存在
        }
        //3,查看站内信是不是自己的(用户id为接收者id)
        HttpSession session= request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getId()!=message.getReceiveUserId()){
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);//禁止访问
        }
        //4,调用dao,把对应id的站内信的状态变动为1:已读
        messageService.updateStateById(id,(byte)1);
        //返回
        return AppResult.success();
    }
    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("要回复的站内信Id") @RequestParam("repliedId") @NonNull Long repliedId,
                           @ApiParam("站内信的内容") @RequestParam("content") @NonNull String content){
        // 校验当前登录⽤⼾的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {//禁言
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 校验要回复的站内信状态
        Message existsMessage = messageService.selectById(repliedId);//通过前端传递的要回复的站内信id来查询对应的信息
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);//资源不存在
        }
        // 不能给⾃⼰回复
        if (user.getId() == existsMessage.getPostUserId()) {//你要回复的站内信的发送者id是自己,那不就凉了
            // 返回错误描述
            return AppResult.failed("不能回复⾃⼰的站内信");
        }
        // 构造对象
        Message message = new Message();//回复给对方的站内信
        message.setPostUserId(user.getId()); //回复给对方站内信的发送者是当前登录用户
        message.setReceiveUserId(existsMessage.getPostUserId()); // 接收者是点击回复的站内信的发送者id
        message.setContent(content); // 内容
        // 调⽤Service
        messageService.reply(repliedId, message);
        // 返回结果
        return AppResult.success();
    }
}
